package redi

import (
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
)

const (
	REDIS_SERVER = "127.0.0.1:6379"
	REDIS_PWD    = "l9yus5nn"
)

var pool *redis.Pool

func init() {
	pool = newPool(REDIS_SERVER, REDIS_PWD)

}
func newPool(server, password string) *redis.Pool {
	return &redis.Pool{

		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if _, err := c.Do("AUTH", password); err != nil {
				c.Close()
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

func Set(name, val string, age int) {
	c := pool.Get()
	defer c.Close()
	c.Do("SET", name, val, "EX", strconv.Itoa(age))

}
func Get(name string) (string, error) {
	c := pool.Get()
	defer c.Close()
	return redis.String(c.Do("GET", name))
}
